#!/usr/bin/env python
# --*-- conding:utf-8 --*--
# @Time : 2024/1/27
# @Author : liangpp
# @Email : mobaicloud@163.com
# @Software : PyCharm


from matplotlib import pylab as plt  # 绘图
from wordcloud import WordCloud as WC  # 生成词云图片
from PIL import Image  # 图片操作
import numpy as np  # 数据操作、科学计算
import jieba  # 中文分词
import pymysql  # 连接mysql数据库


def get_worldcloud_img(filed, src_img, target_img):
    # def get_worldcloud_img(filed, src_img, target_img):
    conn = pymysql.connect(
        host='123.57.193.97',
        port=13306,
        user='lpp',
        password='lpppwd',
        database='car_db',
        charset='utf8mb4',
    )
    cursor = conn.cursor()
    sql = f"select {filed} from carinfo;"
    cursor.execute(sql)
    # data : (('特斯拉中国',), ('东风日产',), ('比亚迪',), ('上汽大众',), ('一汽-大众',), ('比亚迪',), ('比亚迪',), ('比亚迪',),
    data = cursor.fetchall()
    text = ""
    # 将查询到的数据拼接成字符串
    # text : 特斯拉中国东风日产比亚迪
    for d in data:
        if d[0]:
            text = text + d[0]
    conn.commit()
    cursor.close()
    conn.close()

    # jieba库处理 , 将整个字符串分词 按空格切割
    # data_word : 特斯拉 中国 东风 日产 比亚迪
    data_cut_list = jieba.cut(text, cut_all=False)
    data_cut = ' '.join(data_cut_list)
    data_word = data_cut.replace('-', '')
    data_word = data_word.replace('汽车', '')
    # print(data_word)

    # 图片
    img = Image.open(src_img)
    img_array = np.array(img)  # 矩阵
    world_cloud = WC(
        font_path="STHUPO.TTF",
        mask=img_array,
        background_color='#04122c',
    )
    world_cloud.generate_from_text(data_word)

    # 绘图
    plt.imshow(world_cloud)
    plt.axis('off')
    plt.savefig(target_img, dpi=800, bbox_inches='tight', pad_inches=-0.1)


get_worldcloud_img('manufacturer', '../images/car.png', '../images/worldcloud_car.png')
